$(document).ready(function() {
	showLoading(true);
	
	$(".accountName").click(function(){
		showLoading(true);
	});
	
	$(".accountNumber").click(function(){
		showLoading(true);
	});
	
	$("#cancelAccountBtn").button();
	$("#createAccountBtn").button();
	
	$("#createAccLink").click(function() {
		$("#newAcc").fadeIn("normal");
	});

	$("#deleteAccLink").click(function() {
		confirmAccountDeleteAccount();
	});

	$("#cancelAccountBtn").click(function() {
		$("#newAcc").fadeOut("normal");
	});

	calculateBalances();

	invokeWizard();
	
	retrieveEquityDataForUser();
	
	$("#OFXAvailableAmountTR").hide();
	
	$("input[name=uploadStatementType]").click(function(){
		if($(this).val() == "OFX"){ 
			$("#OFXAvailableAmountTR").show();
		}
		else{
			$("#OFXAvailableAmountTR").hide();
		}
	});
});

function retrieveEquityDataForUser(){
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "retrieveEquityDataForUser";
	parms["username"] = "current";

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			
			displayEquityDataGraph(resultData, "Equity");
			showLoading(false);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
	
}


function displayEquityDataGraph(data, itemDescription) {

	var numOfPoints = 0;
	$(data).find("Transaction").each(function(){
		numOfPoints++;
	});
	
	var count = 0;
	var budgetLine = "[";
	$(data).find("Transaction").each(function(){
		count++;
		budgetLine += "['" +$(this).find("date").text()+"',"+ $(this).find("amount").text()+"]"+ (count < numOfPoints ? "," : "]");
	});
	
	if (count == 0) {
		showLoading(false);
		return;
	}
	
	budgetLine = eval(budgetLine);
	plot9 = $.jqplot('chartdiv', [budgetLine], {
	    	title:itemDescription +" Analysis",
	    	seriesDefaults: {
	            showMarker:false,
	            pointLabels: { show:false }
	          },
	    	legend:{show:false},
	     	axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer,
			tickOptions:{formatString:'%b %#d, %Y'}
	    		},
	    	yaxis:{min:0}},
		series:[
		        {label:'Actual', markerOptions:{style:'square'}}, 
		        {label:'Budget'}
		    ]
	});
}

function confirmAccountDeleteAccount() {
	$accountName = $("input:radio[name:'selectAccount']:checked").parent().parent().find(".accountName").html();
	$("#msgDlg").css('font-size', '0.8em');
	$("#msgDlg").html(
			"Are you sure you want to delete the account, '" + $accountName
					+ "' ? All transactions for this account will be deleted.");
	$("#msgDlg").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 300,
		modal : true,
		resizable : false,
		title : "Do you want to delete?",
		buttons : {
			No : function() {
				$(this).dialog("destroy");
			},
			Yes : function() {
				$(this).dialog("destroy");
				deleteAccount($("input:radio[name:'selectAccount']:checked").val());
			}
		}
	});
	$("#msgDlg").dialog("open");
}

function deleteAccount(accountId) {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "deleteAccount";
	parms["accountId"] = accountId;

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			alert("Account deleted successfully.");
			location.reload();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function invokeWizard() {
	var count = 0;
	$(".accountRow").each(function() {
		count++;
	});
	if (count > 0)
		return;

	$("#msgDlg").css('font-size', '0.8em');
	$("#msgDlg")
			.html(
					"You will need to have downloaded your statement so that we can import it and get you started. Do you want to continue?");
	$("#msgDlg").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 400,
		modal : true,
		resizable : false,
		title : "Do you need help?",
		buttons : {
			Yes : function() {
				showWizCreateNewAccount();
				$(this).dialog("destroy");
			},
			No : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#msgDlg").dialog("open");
}

function showWizPage1() {
	$(".wizStep").hide();
	$("#wizardDiv").attr("title", "Page 2/3");
	$("#wizardDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 400,
		modal : true,
		resizable : false,
		title : "Page 1/3",
		buttons : {
			Next : function() {
				$(this).dialog("destroy");
				showWizPage2();
			},
			Cancel : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#wizardDiv").dialog("open");
	$("#wizPage1").show("normal");
}

function showWizPage2() {
	$(".wizStep").hide();
	$("#wizardDiv").attr("title", "Page 2/3");
	$("#wizardDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 400,
		modal : true,
		resizable : false,
		title : "Page 2/3",
		buttons : {
			Next : function() {
				$(this).dialog("destroy");
				uploadStatement();
			},
			Back : function() {
				$(this).dialog("destroy");
				showWizPage1();
			},
			Cancel : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#wizardDiv").dialog("open");
	$("#wizPage2").show("normal");
}

function showWizPage3(data) {
	$("Please confirm the account details before we can create it.").insertBefore("#newAcc");
	$("#accName").val($(data).find("accountName").text());
	$("#accNum").val($(data).find("accountNumber").text());
	$("#openingBal").val($(data).find("openingBalance").text());
	$("#statementBalanceHidden").val($(data).find("statementBalance").text());
	$("#openingBal").attr("disabled", "true");
	$(".wizStep").hide();
	$("#newAccDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 520,
		modal : true,
		resizable : false,
		title : "Page 3/3",
		buttons : {
			Next : function() {
				$("#accNameHidden").val($("#accName").val());
				$("#accNumHidden").val($("#accNum").val());
				$("#openingBalHidden").val($("#openingBal").val());
				$("#budgetStartDateHidden").val($("#budgetStartDate").val());

				uploadStatement();
			},
			Back : function() {
				$(this).dialog("destroy");
				showWizPage2();
			},
			Cancel : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#newAccDiv").dialog("open");
	$("#newAcc").show("normal");
	$("#buttonRow").hide();
}

function showWizCreateNewAccount() {
	var pageTitle = "Upload New Account Statement";
	$(".wizStep").hide();
	$("#wizardDiv").attr("title", pageTitle);
	$("#wizardDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 500,
		modal : true,
		resizable : false,
		title : pageTitle,
		buttons : {
			Next : function() {
				$(this).dialog("destroy");
				uploadStatement();
			},
			Cancel : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#wizardDiv").dialog("open");
	$("#wizCreateNewAccount").show("normal");
}

function uploadStatement() {
	//TODO add validation here
	$("#fileUploadForm").ajaxSubmit( {
		success : function(resultData) {
			var errorCode = $(resultData).find("code").text();
			if (errorCode == 0) {
				createBudget();				
			} else {
				alert($(resultData).find("errMessage").text());
			}
		}
	});
}

function createBudget() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "createCurrentBudget";

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			redirectToNewBudget();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function redirectToNewBudget() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getNewBudgetId";

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			top.location = "/index.php?mod=editBudget&budgetId=" + $(resultData).find("budgetId").text();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function calculateBalances() {
	var total = 0;
	$(".total").each(function() {
		total += eval($(this).html());
		$(this).html(formatCurrency((eval($(this).html())).toFixed(2)));
	});

	$("#equity").html("R " + formatCurrency(total.toFixed(2)));

	$(".stmtTotal").each(function() {
		$(this).html(formatCurrency($(this).html()));
	});

	var usableCashTotal = 0;
	var budgetFunds = 0;
	var budgetRemaingFunds = 0;
	$(".accountRow").each(function() {
		if (($(this).attr("accounttype") == "5") || ($(this).attr("accounttype") == "1")) {
			usableCashTotal += eval($(this).find(".availableBalance").html().replace(",", ""));
		} else if (($(this).attr("accounttype") == "3")) {
			usableCashTotal += eval($(this).find(".total").html().replace(",", ""));
		}
		
		if (($(this).attr("accounttype") == "5")) {
			budgetFunds += eval($(this).find(".availableBalance").html().replace(",", ""));
			budgetRemaingFunds += eval($(this).find(".total").html().replace(",", ""));
		} else if (($(this).attr("accounttype") == "3")) {
			budgetFunds += eval($(this).find(".total").html().replace(",", ""));
			budgetRemaingFunds += eval($(this).find(".total").html().replace(",", ""));
		}
	});
	$("#usableCash").html("R " + formatCurrency(usableCashTotal.toFixed(2)));
	var totalDifference = $("#totalDifference").size() == 0 ? 0 : eval($("#totalDifference").html());
	$("#budgetFunds").html("R " + formatCurrency((totalDifference + budgetFunds).toFixed(2)));
	$("#budgetFundsRemaining").html("R " + formatCurrency((totalDifference + budgetRemaingFunds).toFixed(2)));
	$("#totalDifference").html("R "+ formatCurrency(totalDifference.toFixed(2)));
}

function createAccount() {
	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "createAccount";
	parms["accountName"] = $("#accName").val();
	parms["accountNum"] = $("#accNum").val();
	parms["openingBal"] = $("#openingBal").val();
	parms["accountType"] = "normal";
	if ($("input:radio[name='accountType']:checked").val() == "savings") {
		parms["accountType"] = "expenseSavings";
	} else if ($("input:radio[name='accountType']:checked").val() == "normal") {
		parms["accountType"] = "normal";
	}

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			top.location = "/index.php?mod=myaccounts";
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function hideGraph(){
	$("#chartdiv").hide();
}